package com.wondream.myframework.juc;

import org.junit.Test;

/**
 * @author wondream
 * @version 1.0
 * @create 2022/5/22 4:33 PM
 */
public class JUC04ReentrantLockTest {

    static int staticValue = 0;

    @Test
    public void run() throws InterruptedException {

        final int max = 10;
        final int loopCount = 100000;
        long costTime = 0;

        for (int i = 0; i < max; i++) {
            long start1 = System.nanoTime();
            final JUC04AtomicIntegerWithLock value1 = new JUC04AtomicIntegerWithLock(0);
            Thread[] ts = new Thread[max];
            for (int j = 0; j < max; j++) {
                ts[j] = new Thread(){
                    public void run(){
                        for (int k = 0; k < loopCount; k++) {
                            value1.incrementAndGet();
                        }
                    }
                };
            }
            for (Thread t:
                    ts) {
                t.start();
            }
            for (Thread t:
                    ts) {
                t.join();
            }
            long end1 = System.nanoTime();
            costTime += (end1-start1);
        }
        System.out.println("cost1: " + (costTime));
        System.out.println();

        costTime = 0;
        final Object lock = new Object();
        for (int i = 0; i < max; i++) {
            long start1 = System.nanoTime();
            Thread[] ts = new Thread[max];
            for (int j = 0; j < max; j++) {
                ts[j] = new Thread(){
                  public void run(){
                      synchronized(lock){
                          ++staticValue;
                      }
                  }
                };
            }
            for (Thread t:
                 ts) {
                t.start();
            }
            for (Thread t:
                 ts) {
                t.join();
            }
            long end1 = System.nanoTime();
            costTime +=(end1-start1);
        }
        System.out.println("cost2: " + (costTime));
    }

}
